package com.stox.manager.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.stox.dto.enumeration.SpanType;
import com.stox.manager.BarManager;
import com.stox.manager.ScripManager;
import com.stox.model.Bar;
import com.stox.model.Scrip;
import com.stox.repository.BarRepository;

@Component
@Transactional
public class BarManagerImpl implements BarManager {

	@Autowired
	private BarRepository barRepository;
	
	@Autowired
	private ScripManager scripManager;
	
	@Override
	public void flush() {
		barRepository.flush();
	}

	public List<Bar> findByScripId(Long scripId) {
		return barRepository.findByScripId(scripId);
	}

	@Transactional
	public Bar save(Bar bar) {
		if(null != bar && 
				null != bar.getScrip()){
			Scrip scrip = scripManager.findOne(bar.getScrip().getId());
				if(null == scrip){
					scripManager.saveAndFlush(bar.getScrip());
					barRepository.createPartition(bar.getScrip().getId());
				}else if(!scrip.equals(bar.getScrip())){
					BeanUtils.copyProperties(bar.getScrip(), scrip);
					scripManager.save(scrip);
				}
		}
		return barRepository.save(bar);
	}
	
	@Override
	public List<Bar> findByScripId(Long scripId, SpanType spanType, Date start,int count) {
		return barRepository.findByScripId(scripId, spanType, start, count);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, SpanType spanType, Date start,
			Date end) {
		return barRepository.findByScripId(scripId, spanType, start, end);
	}
	
	@Transactional
	public List<Bar> save(List<Bar> bars) {
		List<Bar> saved = new ArrayList<Bar>(bars.size());
		for(Bar bar : bars) saved.add(save(bar));
		return saved;
	}

}
